import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * GEdgePopup is the popup menu for the edges.
 *
 * @version 1.0
 * @author P.Jaya Krishna
 */
class GEdgePopup extends JPopupMenu implements ActionListener
{
	private JMenuItem invert;
	private JMenuItem delete;
	private JMenuItem properties;
	
	private GPanel gPanel;
	private EdgeAttr currentEdge;
	private int currEdgeFrom;
	private int currEdgeTo;
	
	/**
	 * Creates a popmenu for the edge at the given location (x,y) for the specified GPanel
	 */
	public GEdgePopup(GPanel gPanel, int x, int y)
	{
		this.gPanel = gPanel;
		
		invert       = new JMenuItem("Invert Edge", 'I');
		delete       = new JMenuItem("Delete Edge", 'D');
		properties   = new JMenuItem("Properties", 'P');
		currEdgeFrom = gPanel.getCurrEdgeFrom();
		currEdgeTo   = gPanel.getCurrEdgeTo();
		try
		{
			currentEdge = gPanel.getGraph().getEdge(currEdgeFrom, currEdgeTo);
		}
		catch(IllegalVertexException e)
		{
			// Not a problem even if failed here.
		}
		
		add(invert);
		add(delete);
		addSeparator();
		add(properties);
		
		invert.addActionListener(this);
		delete.addActionListener(this);
		properties.addActionListener(this);
		
		setLocation(x, y);
		show(gPanel, x, y);
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		String s = (String)ae.getActionCommand();
		
		if(s.equals("Invert Edge"))
		{
			try
			{
				if(gPanel.getGraph().edgeExists(currEdgeTo, currEdgeFrom))
				{
					gPanel.addUndo();
					gPanel.getGraph().setEdge(currEdgeTo, currEdgeFrom, currentEdge);
				}
				else
				{
					gPanel.addUndo();
					gPanel.getGraph().addEdge(currEdgeTo, currEdgeFrom, currentEdge);
				}
				gPanel.getGraph().removeEdge(currEdgeFrom, currEdgeTo);
			}
			catch(IllegalVertexException e)
			{
				// Not a problem even if failed here.
			}
		}
		else if(s.equals("Delete Edge"))
		{
			try
			{
				gPanel.addUndo();
				gPanel.getGraph().removeEdge(currEdgeFrom, currEdgeTo);
			}
			catch(IllegalVertexException e)
			{
				// Not a problem even if failed here.
			}			
		}
		else if(s.equals("Properties"))
		{
			new GEdgeDialog(gPanel, currentEdge);
			
			try
			{
				gPanel.addUndo();
				gPanel.getGraph().setEdge(currEdgeFrom, currEdgeTo, currentEdge);
			}
			catch(IllegalVertexException e)
			{
				// Not a problem even if failed here.
			}
		}
		gPanel.repaint();
	}
}